package com.ls.io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/16 16:25
 * @since
 */
public class NettyServerMultiThreadRead {

    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap bs = new ServerBootstrap();
        ChannelFuture bind = bs.group(new NioEventLoopGroup(1), new NioEventLoopGroup(5))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReadHandler());
                    }
                })
                .bind(8088);

        bind.sync().channel().closeFuture().sync();

    }

}


class ReadHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("outer thread: " + Thread.currentThread().getName() + " exec : read");

        ctx.executor().parent().next().execute(() ->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            ByteBuf buf = (ByteBuf) msg;
            CharSequence str =
                    buf.getCharSequence(buf.readerIndex(), buf.readableBytes(), Charset.forName("utf-8"));
            System.out.println("read:" + str);

            System.out.println("inner thread: " + Thread.currentThread().getName() + " exec : write");

            ctx.writeAndFlush(buf);
        });
    }
}